package _2022.hot100._19_删除链表的倒数第N个结点;


/**
 * @author： YHSimon
 * @date： 2022-04-01 14:02
 */

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {

    public ListNode removeNthFromEnd2(ListNode head,int n){
        ListNode preHead=new ListNode(-1,head);
        ListNode slow=preHead;
        ListNode fast=head;
        for(int i=0;i<n;i++){
            fast=fast.next;
        }
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return preHead.next;
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode preHead = new ListNode(-1);
        preHead.next=head;
        int len=0;
        while(head!=null){
            head=head.next;
            len++;
        }
        head=preHead.next;
        int target=len+1-n;
        if(target<=0){
            return null;
        }
        int cur=1;
        ListNode pre=preHead;
        while(head!=null){
            if(cur==target){
                pre.next=head.next;
                return preHead.next;
            }
            cur++;
            pre=head;
            head=head.next;
        }

        return preHead.next;
    }

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        root.next=new ListNode(2);
        Solution s = new Solution();
        ListNode res=s.removeNthFromEnd(root, 1);
        while(res!=null){
            System.out.println(res.val+' ');
            res=res.next;
        }
    }
}
